<?php
// +----------------------------------------------------------------------
// | OneThink [ WE CAN DO IT JUST THINK IT ]
// +----------------------------------------------------------------------
// | Copyright (c) 2013 http://www.onethink.cn All rights reserved.
// +----------------------------------------------------------------------
// | Author: huajie <banhuajie@163.com>
// +----------------------------------------------------------------------
namespace Admin\Controller;
use Admin\Model\AuthGroupModel;
use Think\Page;

/**
 * 后台内容控制器
 * @author huajie <banhuajie@163.com>
 */
class OrderController extends ThinkController {

    /* 保存允许访问的公共方法 */
    static protected $allow = array( 'draftbox','order');

    public function lists($model = null, $p = 0){
        $data = (I('get.'));
        if(isset($data['type'])){
            $type = $data['type'];
        }else{
            $type = 0;
        }

        $model || $this->error('模型名标识必须！');
        $page = intval($p);
        $page = $page ? $page : 1; //默认显示第一页数据
       
        //获取模型信息
        $model = M('Model')->getByName($model);
        $model || $this->error('模型不存在！');

        //解析列表规则
        $fields = array();
        $grids  = preg_split('/[;\r\n]+/s', trim($model['list_grid']));
        foreach ($grids as &$value) {
            if(trim($value) === ''){
                continue;
            }
            // 字段:标题:链接
            $val      = explode(':', $value);
            // 支持多个字段显示
            $field   = explode(',', $val[0]);
            $value    = array('field' => $field, 'title' => $val[1]);
            if(isset($val[2])){
                // 链接信息
                $value['href']  =   $val[2];
                // 搜索链接信息中的字段信息
                preg_replace_callback('/\[([a-z_]+)\]/', function($match) use(&$fields){$fields[]=$match[1];}, $value['href']);
            }
            if(strpos($val[1],'|')){
                // 显示格式定义
                list($value['title'],$value['format'])    =   explode('|',$val[1]);
            }
            foreach($field as $val){
                $array  =   explode('|',$val);
                $fields[] = $array[0];
            }
        }
        // 过滤重复字段信息
        $fields =   array_unique($fields);
        // 关键字搜索
        $map    =   array();
        $key    =   $model['search_key']?$model['search_key']:'title';
        if(isset($_REQUEST[$key])){
            $map[$key]  =   array('like','%'.$_GET[$key].'%');
            unset($_REQUEST[$key]);
        }
        // 条件搜索
        foreach($_REQUEST as $name=>$val){
            if(in_array($name,$fields)){
                $map[$name] =   $val;
            }
        }
        $row    = empty($model['list_row']) ? 10 : $model['list_row'];

        //$map['status'] = 1;
        if($type=='1'){
            // 未支付的订单 
            $map['status'] = 1;
        }
        if($type=='2'){
            // 已经支付的订单 
            $map['status'] = array('in','3,5');
        }
        if($type=='3'){
            // 已完成的订单 
            $map['status'] = 6;
        }
        if($type=='4'){
            // 未支付取消的
            $map['status'] = 2;
        }
        if($type=='5'){
            // 需要退款的
            $map['status'] = 4;
        }
        //读取模型数据列表
        if($model['extend']){
            $name   = get_table_name($model['id']);
            $parent = get_table_name($model['extend']);
            $fix    = C("DB_PREFIX");

            $key = array_search('id', $fields);
            if(false === $key){
                array_push($fields, "{$fix}{$parent}.id as id");
            } else {
                $fields[$key] = "{$fix}{$parent}.id as id";
            }

            /* 查询记录数 */
            $count = M($parent)->join("INNER JOIN {$fix}{$name} ON {$fix}{$parent}.id = {$fix}{$name}.id")->where($map)->count();

            // 查询数据
            $data   = M($parent)
                ->join("INNER JOIN {$fix}{$name} ON {$fix}{$parent}.id = {$fix}{$name}.id")
                /* 查询指定字段，不指定则查询所有字段 */
                ->field(empty($fields) ? true : $fields)
                // 查询条件
                ->where($map)
                /* 默认通过id逆序排列 */
                ->order("{$fix}{$parent}.id DESC")
                /* 数据分页 */
                ->page($page, $row)
                /* 执行查询 */
                ->select();

        } else {
            if($model['need_pk']){
                in_array('id', $fields) || array_push($fields, 'id');
            }
            $name = parse_name(get_table_name($model['id']), true);
            $data = M($name)
                /* 查询指定字段，不指定则查询所有字段 */
                ->field(empty($fields) ? true : $fields)
                // 查询条件
                ->where($map)
                /* 默认通过id逆序排列 */
                ->order($model['need_pk']?'id DESC':'')
                /* 数据分页 */
                ->page($page, $row)
                /* 执行查询 */
                ->select();

            /* 查询记录总数 */
            $count = M($name)->where($map)->count();
        }

        //分页
        if($count > $row){
            $page = new \Think\Page($count, $row);
            $page->setConfig('theme','%FIRST% %UP_PAGE% %LINK_PAGE% %DOWN_PAGE% %END% %HEADER%');
            $this->assign('_page', $page->show());
        }
       
        $data   =   $this->parseDocumentList($data,$model['id']);
        $this->assign('model', $model);
        $this->assign('list_grids', $grids);
        $this->assign('list_data', $data);
        $this->meta_title = $model['title'].'列表';
        $this->display($model['template_list']);
    }

    public function edit($model = null, $id = 0){
        //获取模型信息
        $model = M('Model')->find($model);
        $model || $this->error('模型不存在！');

        if(IS_POST){
            $Model  =   D(parse_name(get_table_name($model['id']),1));
            // 获取模型的字段信息
            $Model  =   $this->checkAttr($Model,$model['id']);
            if($Model->create() && $Model->save()){
                $this->success('保存'.$model['title'].'成功！', U('lists?model='.$model['name']));
            } else {
                $this->error($Model->getError());
            }
        } else {
            $fields     = get_model_attribute($model['id']);

            //获取数据
            $data       = M(get_table_name($model['id']))->find($id);
            $data || $this->error('数据不存在！');
            if($data['article_id']){
                $articleshowModel = D('articleshow');
                $articleshow_data = $articleshowModel->getFieldById($data['article_id'],'title');
            }
            $data['article_title'] = $articleshow_data['title'];
            if($data['project'] == 1){

                $contacts_data = M('contacts')->where('order_id='.$data['id'])->select();
                $sex_array = C('sex');
                $oneday_ticket_type =C('oneday_ticket_type');
                foreach ($contacts_data as $key => $value) {
                   $data['contacts'][$key] = array(
                    'contact_name'      => $value['contact_name']?$value['contact_name']:'',
                    'sex'               => $sex_array[$value['sex']]?$sex_array[$value['sex']]:'',
                    'contact_mobile'    => $value['contact_mobile']?$value['contact_mobile']:'',
                    'identity_card'          => $value['identity_card'],
                    'birthday'          => $value['birthday']?$value['birthday']:'',
                    'birth'             => $card_type[$value['birth']]?$card_type[$value['birth']]:'身份证',
                    'contact_type'      => $oneday_ticket_type[$value['contact_type']],
                    );
                }
                $onedaydetail = M('onedaydetail')->where('order_id='.$data['id'])->select();
                $oneday_detail = array(
                    'tour_time' => date('Y-m-d h-i-s',$onedaydetail['0']['tour_time']), 
                    'venue'     => $onedaydetail['0']['venue'],
                    'need_english'=> $onedaydetail['0']['need_english']==1?'不需要':'需要',
                    'contact_name'=>$onedaydetail['0']['contact_person'],
                    'contact_num' =>$onedaydetail['0']['contact_num'],
                    );
            }else{
                $disneydetail = M('disneydetail')->where('order_id='.$data['id'])->select();
                $disney_detail = array(
                    'tour_time' => date('Y-m-d h-i-s',  $disneydetail['0']['tour_time']),
                    'num'       => $disneydetail['0']['num'],
                    );
                $contacts_data = M('contacts')->where('order_id='.$data['id'])->select();
                $sex_array = C('sex');
                $disney_ticket_type =C('disney_ticket_type');
                foreach ($contacts_data as $key => $value) {
                   $data['contacts'][$key] = array(
                    'contact_name'      => $value['contact_name']?$value['contact_name']:'',
                    'sex'               => $sex_array[$value['sex']]?$sex_array[$value['sex']]:'',
                    'contact_mobile'    => $value['contact_mobile']?$value['contact_mobile']:'',
                    'identity_card'          => $value['identity_card'],
                    'birthday'          => $value['birthday']?$value['birthday']:'',
                    'birth'             => $card_type[$value['birth']]?$card_type[$value['birth']]:'身份证',
                    'contact_type'      => $disney_ticket_type[$value['contact_type']],
                    );
                }
            }
            $this->assign('model', $model);
            $this->assign('fields', $fields);
            $this->assign('data', $data);
            if($oneday_detail){
                $this->assign('onedaydetail',$oneday_detail);
            }
            if($disney_detail){
                $this->assign('disneydetail',$disney_detail);
            }
            $this->meta_title = '编辑'.$model['title'];
            $this->display($model['template_edit']?$model['template_edit']:'');
        }
    }
    public function sendTicket($id){
        $desninfo =M('disneydetail')
                ->join("`order` on order.id =disneydetail.order_id")
                ->where(array('order_id'=>$id))
                ->find();
        $neednum =intval($desninfo['num']);
        $nums =array();
        for ($i=0; $i < $neednum; $i++) { 
            $nums[]['name']=$i+1;
        }
        
        $this->assign('data',$desninfo);
        $this->assign('num',$nums);
        $this->display('tickets');
    }
    public function addTickets(){
        $post =$_POST;
        $id =$post['id'];
        unset($post['id']);
        $allnum =$post['neednum'];
        unset($post['neednum']);
        $sendnum =count($post);
        foreach ($post as $key => $value) {
           if($value==''){
                $this->error("票券数不足");
           }
        }
       
        $needs =array_merge($post);
        $nums =json_encode($needs);
        $contact = M('contacts')->where(array('order_id'=>$id))->find();
        $data['tickets'] =$nums;
        $status['status'] =5;
        $order =M('order')->where(array('id'=>$id))->save($status);

        $save  = M('contacts')->where(array('order_id'=>$id))->save($data);
        $url = U("Order/lists",array('model'=>'order','type'=>2));
      
        $this->success("发券成功",$url);
    }
    public function remoney($id){
        $record =M('record')
                    ->where(array('order_id'=>$id))
                    ->find();
        $order =M('order')->find($id);
        if($record&&$order['status']=='4'){
            $save['status'] =7;//退款中
            $re =M('order')->where(array('id'=>$id))->save($save);
        }
        $this->success("操作成功");
    }

   
}